<template>
    <el-card class="box-card">
        <template #header>
            <div class="card-header">
                <span class="font-bold">标签管理</span>
            </div>
        </template>
        <template #default>
            <el-form :inline="true" :model="labelform" class="demo-form-inline" ref="elform">
                <el-form-item label="搜索标签" prop="labelname">
                    <el-input v-model="labelform.labelname" placeholder="标签名字" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit($event)">
                        <el-icon class="-ml-1">
                            <Search />
                        </el-icon>搜索</el-button>
                    <el-button type="primary" @click="restart(elform)">重置</el-button>
                </el-form-item>

            </el-form>

            <el-row :gutter="20" class="mb-1">
                <el-col :span="3">
                    <el-button type="danger" :icon="Delete" size="small" @click="handleClick()">批量删除</el-button>
                </el-col>
                <el-col :span="3" :offset="18">
                    <el-button type="primary" :icon="Plus" size="small" @click="bianjiAndadd()">添加</el-button>
                </el-col>
            </el-row>

            <el-table ref="multipleTableRef" :data="tableData" size="small" highlight-current-row border
            lazy  :row-key="(row)=>{ return row.id}" 
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" :reserve-selection="true"/>
                <el-table-column type="index" label="序号" align="center" />
                <el-table-column label="标签" width="250" align="center">
                    <template #default="scope">{{ scope.row.name }}</template>
                </el-table-column>
                <el-table-column property="creatrtime" label="创建日期" width="250" align="center" />
                <el-table-column property="updatatime" label="修改日期" width="250" align="center" />
                <el-table-column label="标签" width="185" align="center">
                    <template #default="scope">
                        <el-button link type="primary" size="small"
                            @click="bianjiAndadd(scope.row.name, scope.row.id)">编辑</el-button>
                        <el-popover :visible="scope.row.visible" placement="top" :width="160">
                            <div class="mt-2">
                                <p>确定要删除吗?</p>
                                <el-button size="small" type="primary" @click="scope.row.visible = false">取消</el-button>
                                <el-button size="small" type="danger" @click="handleClick('single', scope)">确定</el-button>
                            </div>
                            <template #reference>
                                <el-button link type="danger" size="small" @click="getcurrentvisible(scope)">删除</el-button>
                            </template>
                        </el-popover>
                    </template>
                </el-table-column>
            </el-table>
            <pagination :currentPage="allcurrentPage" :pageSize="allpageSize" :total="alltotal" :loading="loading"
                @updatepage="changepage"></pagination>
        </template>
    </el-card>
    <!-- 输入框 -->
    <Dialogg :istoshow="showeidit" title="编辑" @cansol="cansol">
        <template #body>
            <el-form :model="form" width="30%" :rules="rules" ref="edit">
                <el-form-item label="名字" label-width="70px" prop="name">
                    <el-input v-model="form.name" autocomplete="off" />
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="cansol">取消</el-button>
                <el-button type="primary" @click="subandclose('编辑', edit)">
                    确定
                </el-button>
            </span>
        </template>
    </Dialogg>
    <Dialogg :istoshow="showadd" title="添加" @cansol="cansol">
        <template #body>
            <el-form :model="form" width="20%" ref="addref" :rules="rules">
                <el-form-item label="名字" label-width="70px" prop="name">
                    <el-input v-model="form.name" autocomplete="off" />
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="cansol">取消</el-button>
                <el-button type="primary" @click="subandclose('添加', addref)">
                    确定
                </el-button>
            </span>
        </template>
    </Dialogg>
</template>

<script setup>
import { ref, reactive, onMounted, inject, nextTick, watch } from 'vue'
import pagination from '@/components/pagination.vue'
import Dialogg from '@/components/dialog.vue';
import { Userstore } from "@/store/User.js"
import moment from "moment";
import {
    Search,
    Delete,
    Plus
} from '@element-plus/icons-vue'
import {
    getlablecount,
    getlables,
    addlable,
    deleteLable,
    searchlable,
    editlables,
    deleteList
} from "@/api/lable.js"
let reload = inject('reload')
let usestore = Userstore()
/* 分页器的数据和方法 */
let allcurrentPage = ref(1)
let allpageSize = ref(9)
let alltotal = ref(0)
let loading = ref(false)
/* 当搜索的时候临时暂存当前的页面 */
let tempcurrentpage = ref(1)
let tempalltotal = ref(9)
let iszhefirstSerch = true // 是否是第一次搜索
/* 搜索框里面的数据 */
const labelform = reactive({
    labelname: '',
})
/* 修改页码 */
async function changepage(page) {
    allcurrentPage.value = page
    if (iszhefirstSerch) {
        await getlabless()
    } else {
        await onSubmit(null, allcurrentPage.value)
    }
}
watch(() => labelform.labelname, (newval, oldval) => {
    if (newval == "") {
        allcurrentPage.value = tempcurrentpage.value;
        alltotal.value = tempalltotal.value;
        iszhefirstSerch = true
        getlabless()
    }
})
/* dom元素  */
const elform = ref();
const multipleTableRef = ref()
/* 要删除的数据 */
let deletedata = ref([])
/* 校验规则 */
const rules = ref({
    name: [
        { required: true, message: '内容不能为空', trigger: 'blur' },
    ]
})
/* 标签内的数据 */
let tableData = ref([])
onMounted(async () => {
    /* 先获取标签的总数 */
    try {
        let res = await getlablecount()
        if (res.data.status == 200) {
            alltotal.value = res.data.data
            await getlabless()
        }
    } catch (error) {
        console.log(error);
    }
})
/* 获取标签 */
async function getlabless() {
    loading.value = true
    let isok = await getlables({ pageIndex: allcurrentPage.value, pageSize: allpageSize.value })
    loading.value = false
    if (isok.data.status == 200) {
        tableData.value = isok.data.data.map((item) => {
            let creatrtime = moment(item.createdAt).format("YYYY-MM-DD HH:mm:ss")
            let updatatime = moment(item.updatedAt).format("YYYY-MM-DD HH:mm:ss")
            return {
                id: item.id,
                name: item.lable_name,
                updatatime,
                creatrtime,
                visible: false,
            }
        })
        return tableData.value
    } else {
        ElMessage({
            message: '获取失败',
            type: 'warning',
        })
    }
}
/* 编辑和添加变量 */
let edit = ref(null)
let addref = ref(null)
let showeidit = ref(false)
let showadd = ref(false)
/* 编辑和添加的时候共用的变量 */
let form = reactive({
    name: '',
    lable_id: null,
})
function cansol() {
    showeidit.value = false
    showadd.value = false
    form.name = ''
}
/* 添标签的关闭按钮 */
async function subandclose(data, reff) {
    if (data == "编辑") {
        /* 非空校验 */
        reff.validate(async (valid, fields) => {
            if (valid) {
                showeidit.value = false
                let res = await editlables({
                    lablename: form.name,
                    id: usestore.userInfo.id,
                    lable_id: form.lable_id
                })
                if (res.data.status == 200) {
                    ElMessage({
                        message: '修改成功',
                        type: 'success',
                    })
                    reload()
                } else {
                    ElMessage({
                        message: `${res.data.message}`,
                        type: 'warning',
                    })
                }
                form.name = ''
            } else {
                ElMessage({
                    message: '请填写信息',
                    type: 'warning',
                })
            }
        })
    } else {
        /* 添加 */
        reff.validate(async (valid, fields) => {
            if (valid) {
                /* 校验通过发送请求 */
                let res = await addlable(form.name, usestore.userInfo.id);
                if (res.data.status == 200) {
                    /* 刷新页面  */
                    reload()
                    ElMessage({
                        message: '添加成功',
                        type: 'success',
                    })
                } else {
                    ElMessage({
                        message: '添加失败',
                        type: 'warning',
                    })
                }
                showadd.value = false
                form.name = ''
            } else {
                console.log('error submit!', fields)
            }
        })
    }
}
/* 编辑和添加显示 */
const bianjiAndadd = (name, id) => {
    if (name) {
        form.name = name
        form.lable_id = id
        showeidit.value = true
    } else {

        showadd.value = true
    }
}
/* 显示删除的提示框 */
function getcurrentvisible(data) {
    data.row.visible = true;
}
/* 删除标签 */
async function handleClick(flge, data) {
    /* 单个删除 */
    if (flge == "single") {
        let res = await deleteLable({ id: usestore.userInfo.id, lable_id: data.row.id })
        if (res.data.status == 200) {
            ElMessage({
                message: `${res.data.message}`,
                type: 'success',
            })
        } else {
            ElMessage({
                message: `${res.data.message}`,
                type: 'warning',
            })
        }
        data.row.visible = false;
        reload()
    } else {
        /* 批量删除 */
        if (!deletedata.value.length) {
            ElMessage({
                message: '请选择',
                type: 'warning',
            })
        } else {
            /* 这里删除 */
            let lablelist = deletedata.value.map(item=>{
                return item.id
            })
            let res = await deleteList({
                id: usestore.userInfo.id,
                lablelist:lablelist
            })
            if(res.data.status==200){
                ElMessage({
                    message: `${res.data.message},删除个数为${res.data.data.num}`,
                    type:'success'
                })
                reload()
            }else{
                ElMessage({
                    message: `${res.data.message}`,
                    type:'warning'
                })
            }
        }
    }

}
/* 点击勾选框添加要删除的行 */
const handleSelectionChange = (val) => {
    if (!val.length) {
        deletedata.value = [];
        return
    }
    deletedata.value = val
}
/* 按名字搜索标签  keyword, pageinfo*/
const onSubmit = async (e, page) => {
    if (labelform.labelname == '') {
        ElMessage({
            message: `请输入标签名称`,
            type: 'warning',
        })
    } else {
        if (iszhefirstSerch) {
            tempcurrentpage.value = allcurrentPage.value;
            tempalltotal.value = alltotal.value;
            allcurrentPage.value = 1;
            iszhefirstSerch = false;
        } else {
            if (page) {
                allcurrentPage.value = page
            } else {
                allcurrentPage.value = 1;
                console.log(allcurrentPage);
            }
        }
        let res = await searchlable({ keyword: labelform.labelname, pageinfo: { pageIndex: allcurrentPage.value, pageSize: allpageSize.value } })
        if (res.data.status == 200) {
            alltotal.value = res.data.data.num;
            tableData.value = res.data.data.data.map(item => {
                let creatrtime = moment(item.createdAt).format("YYYY-MM-DD HH:mm:ss")
                let updatatime = moment(item.updatedAt).format("YYYY-MM-DD HH:mm:ss")
                return {
                    id: item.id,
                    name: item.lable_name,
                    updatatime,
                    creatrtime,
                    visible: false,
                }
            });
        }
    }
}
/* 重置搜索框 */
const restart = (formx) => {
    formx.resetFields();
}
</script>

<style lang="css" scoped>
.demo-form-inline .el-input {
    --el-input-width: 220px;
}

:deep(.el-card__header) {
    padding: 5px 10px !important;
}

:deep(.el-table .el-table__cell) {
    padding: 0px 0px !important;
}
</style>